package com.wxp.cloud.stream.controller;

import com.wxp.cloud.common.result.Result;
import com.wxp.cloud.stream.enums.MessageTagEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageConst;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 消息控制器
 *
 * @author wxp
 * @version 1.0
 * @description: 消息控制器
 * @date 2022/4/2 18:35
 */
@Slf4j
@Api(tags = "消息控制器")
@RequestMapping("/stream/message")
@RestController
public class MessageController {

    @Resource
    private Source source;

    /**
     * 发送简单消息
     *
     * @param msg 消息
     * @return 响应结果
     */
    @ApiOperation(value = "发送消息", notes = "发送消息")
    @GetMapping("/send/{msg}")
    public Result<String> send(@PathVariable("msg") String msg) {
        //定义参数
        Map<String, Object> headers = new HashMap<>(16);
        //定义消息标签
        headers.put(MessageConst.PROPERTY_TAGS, MessageTagEnum.TAG_A);
        //定义消息头对象
        MessageHeaders messageHeaders = new MessageHeaders(headers);
        //创建消息
        Message<String> message = MessageBuilder.createMessage(msg, messageHeaders);
        //发送消息
        boolean send = source.output().send(message);
        return Result.okMessage(send ? "发送成功" : "发送失败");
    }

}
